import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/single_chat_print.dart';
import 'package:thal/backstage/blueprint/user_print.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/single_chat_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/playbill/auth_sage/login_production.dart';
import 'package:thal/playbill/messenger/single_chat_production.dart';

part 'chat_production.page.dart';

/// 聊天页面
@PagePath('/chat')
class ChatProduction extends StatelessWidget {
  const ChatProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$ChatProductionQuery().call();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(bottom: false, child: _buildContent(context)),
      ),
    );
  }

  /// 构建内容
  Widget _buildContent(BuildContext context) {
    final userRoom = GlobalStateProvider.userRoomOf(context);

    // 使用Observer来响应登录状态变化
    return Observer(
      builder: (_) {
        // 检查是否登录
        if (!userRoom.isLoggedIn) {
          return _buildNotLoggedInContent(context);
        }

        return Column(
          children: [
            // 固定顶部标题
            _buildFixedHeader(),

            // 可滚动内容区域
            Expanded(
              child: Column(
                children: [
                  // 推荐用户列表
                  _buildRecommendedUsers(context).wrapHorizontal(16.w),
                  24.h.heightBox,

                  // 单聊列表 - 占据剩余空间
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 2.w),
                      width: double.infinity,
                      decoration: BoxDecoration(
                        color: ColorPalette.white,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(26.r),
                          topRight: Radius.circular(26.r),
                        ),
                      ),
                      child: SingleChildScrollView(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: _buildSingleChatList(context),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  /// 构建未登录内容
  Widget _buildNotLoggedInContent(BuildContext context) {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 装饰图片
            Image.asset(
              AssetManifest.panda,
              width: 200.w,
              height: 200.w,
              fit: BoxFit.contain,
            ),

            40.h.heightBox,

            // 提示信息
            Text('Please login to view messages', textAlign: TextAlign.center)
                .fontSize(20.sp)
                .textColor(ColorPalette.black)
                .arimo(weight: FontWeight.bold),

            16.h.heightBox,

            Text(
                  'Login to start chatting with other users',
                  textAlign: TextAlign.center,
                )
                .fontSize(14.sp)
                .textColor(ColorPalette.black.withValues(alpha: 0.6))
                .arimo(),

            40.h.heightBox,

            // 登录按钮
            Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(vertical: 16.h),
              decoration: BoxDecoration(
                color: ColorPalette.blue1,
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Text('Go to Login', textAlign: TextAlign.center)
                  .fontSize(16.sp)
                  .textColor(ColorPalette.white)
                  .arimo(weight: FontWeight.w600),
            ).withTapEffect(
              onTap: () {
                context.router.push(LoginProduction.query());
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 构建固定顶部标题
  Widget _buildFixedHeader() {
    return Row(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
          child: Text('Chats')
              .fontSize(24.sp)
              .textColor(ColorPalette.black)
              .carterOne(weight: FontWeight.w400),
        ),
      ],
    );
  }

  /// 构建推荐用户列表
  Widget _buildRecommendedUsers(BuildContext context) {
    final userRoom = GlobalStateProvider.userRoomOf(context);
    final singleChatRoom = GlobalStateProvider.singleChatRoomOf(context);
    final currentUser = userRoom.fetchCurrentUser();

    if (currentUser == null) return SizedBox.shrink();

    // 获取所有用户，排除当前用户
    final allUsers =
        userRoom.users.where((user) => user.id != currentUser.id).toList();

    // 按ID排序以确保顺序稳定
    final recommendedUsers = List<UserPrint>.from(allUsers)
      ..sort((a, b) => a.id.compareTo(b.id));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 70.h,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: recommendedUsers.length,
            itemBuilder: (context, index) {
              final user = recommendedUsers[index];
              // 基于用户ID生成稳定的在线状态
              final isOnline = _getStableOnlineStatus(user.id);

              return Padding(
                padding: EdgeInsets.only(right: 12.w),
                child: _buildRecommendedUserAvatar(
                  context,
                  user,
                  isOnline,
                  singleChatRoom,
                  currentUser.id,
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  /// 获取稳定的在线状态（基于用户ID）
  bool _getStableOnlineStatus(String userId) {
    // 使用用户ID的哈希值来决定在线状态
    final hashCode = userId.hashCode;
    // 通过模运算决定是否在线，保持稳定性
    return hashCode % 3 != 0; // 大约66%的用户在线
  }

  /// 构建推荐用户头像
  Widget _buildRecommendedUserAvatar(
    BuildContext context,
    UserPrint user,
    bool isOnline,
    SingleChatRoom singleChatRoom,
    String currentUserId,
  ) {
    return GestureDetector(
      onTap: () {
        // 创建或获取单聊
        final chatId = singleChatRoom.createSingleChat(currentUserId, user.id);
        // 跳转到单聊详情页面
        context.router.push(SingleChatProduction.query(chatId: chatId));
      },
      child: Stack(
        alignment: Alignment.bottomRight,
        children: [
          // 用户头像
          Container(
            width: 60.w,
            height: 60.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30.r),
              border: Border.all(
                color:
                    isOnline
                        ? ColorPalette.blue1
                        : ColorPalette.black.withValues(alpha: 0.1),
                width: 2.w,
              ),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(30.r),
              child: Image.asset(user.avatar, fit: BoxFit.cover),
            ),
          ),
          // 在线状态指示器
          Container(
            width: 16.w,
            height: 16.w,
            decoration: BoxDecoration(
              color: isOnline ? Colors.green : Colors.grey,
              shape: BoxShape.circle,
              border: Border.all(color: ColorPalette.white, width: 2.w),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建单聊列表
  Widget _buildSingleChatList(BuildContext context) {
    final userRoom = GlobalStateProvider.userRoomOf(context);
    final singleChatRoom = GlobalStateProvider.singleChatRoomOf(context);
    final currentUser = userRoom.fetchCurrentUser();

    if (currentUser == null) return SizedBox.shrink();

    final userChats = singleChatRoom.fetchUserSingleChats(currentUser.id);

    if (userChats.isEmpty) {
      return Center(
        child: Padding(
          padding: EdgeInsets.only(top: 40.h),
          child:
              Text('No messages yet')
                  .fontSize(14.sp)
                  .textColor(ColorPalette.black.withValues(alpha: 0.6))
                  .arimo(),
        ),
      );
    }

    return Column(
      children: [
        // 顶部 padding
        16.h.heightBox,
        // 单聊列表项
        ...userChats.map((chat) {
          // 获取对方用户ID
          final otherUserId =
              chat.userId1 == currentUser.id ? chat.userId2 : chat.userId1;
          final otherUser = userRoom.fetchUserById(otherUserId);
          final latestMessage = singleChatRoom.fetchLatestSingleChatMessage(
            chat.id,
          );

          return _buildSingleChatItem(context, chat, otherUser, latestMessage);
        }).toList(),
        // 底部 padding
        105.h.heightBox,
      ],
    );
  }

  /// 构建单个单聊项
  Widget _buildSingleChatItem(
    BuildContext context,
    SingleChatPrint chat,
    UserPrint? otherUser,
    SingleChatMessagePrint? latestMessage,
  ) {
    // 基于用户ID生成稳定的在线状态
    final isOnline =
        otherUser != null ? _getStableOnlineStatus(otherUser.id) : false;

    return GestureDetector(
      onTap: () {
        context.router.push(SingleChatProduction.query(chatId: chat.id));
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 12.h),
        padding: EdgeInsets.all(12.w),
        decoration: BoxDecoration(
          color: ColorPalette.white,
          borderRadius: BorderRadius.circular(16.r),
          boxShadow: [
            BoxShadow(
              color: ColorPalette.black.withValues(alpha: 0.05),
              blurRadius: 8,
              offset: Offset(0, 2.h),
            ),
          ],
        ),
        child: Row(
          children: [
            // 用户头像
            Stack(
              alignment: Alignment.bottomRight,
              children: [
                Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(30.r),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(30.r),
                    child: Image.asset(
                      otherUser?.avatar ?? AssetManifest.avatar1,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                // 在线状态指示器
                Container(
                  width: 16.w,
                  height: 16.w,
                  decoration: BoxDecoration(
                    color: isOnline ? Colors.green : Colors.grey,
                    shape: BoxShape.circle,
                    border: Border.all(color: ColorPalette.white, width: 2.w),
                  ),
                ),
              ],
            ),

            16.w.widthBox,

            // 用户信息和消息预览
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户名和时间
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(otherUser?.username ?? 'Unknown')
                          .fontSize(16.sp)
                          .textColor(ColorPalette.black)
                          .arimo(weight: FontWeight.w600),
                      if (latestMessage != null)
                        Text(_formatTime(latestMessage.createdAt))
                            .fontSize(12.sp)
                            .textColor(
                              ColorPalette.black.withValues(alpha: 0.6),
                            )
                            .arimo(),
                    ],
                  ),

                  4.h.heightBox,

                  // 最后一条消息预览
                  Text(
                        latestMessage != null
                            ? _getMessagePreview(latestMessage)
                            : 'No messages yet',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      )
                      .fontSize(14.sp)
                      .textColor(ColorPalette.black.withValues(alpha: 0.6))
                      .arimo(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取消息预览
  String _getMessagePreview(SingleChatMessagePrint message) {
    if (message.messageType == 'text') {
      return message.content;
    } else if (message.messageType == 'call_failed') {
      return 'Call failed';
    } else if (message.messageType == 'call_missed') {
      return 'Missed call';
    } else {
      return message.content;
    }
  }

  /// 格式化时间
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final messageDate = DateTime(dateTime.year, dateTime.month, dateTime.day);

    // 检查是否今天
    if (messageDate.isAtSameMomentAs(today)) {
      return _formatTimeWithAMPM(dateTime);
    }

    // 检查是否昨天
    if (messageDate.isAtSameMomentAs(yesterday)) {
      return 'Yesterday';
    }

    // 检查是否在同一周内
    final daysDifference = today.difference(messageDate).inDays;
    if (daysDifference > 1 && daysDifference <= 7) {
      return _getWeekdayName(dateTime);
    }

    // 超过一周，显示日期
    return '${dateTime.day}/${dateTime.month}/${dateTime.year}';
  }

  /// 格式化为AM/PM时间
  String _formatTimeWithAMPM(DateTime dateTime) {
    final hour = dateTime.hour;
    final minute = dateTime.minute;
    final period = hour >= 12 ? 'PM' : 'AM';
    final displayHour = hour == 0 ? 12 : (hour > 12 ? hour - 12 : hour);
    final displayMinute = minute.toString().padLeft(2, '0');
    return '$displayHour:$displayMinute $period';
  }

  /// 获取星期几的名称
  String _getWeekdayName(DateTime dateTime) {
    const weekdays = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday',
    ];
    return weekdays[dateTime.weekday - 1];
  }
}
